/**
 * 招聘模块状态管理
 * @module store/modules/recruit
 * @author 互成一家团队
 * @description 招聘模块的Vuex状态管理
 */

import {
  getRecruitList,
  getRecruitDetail,
  getUserApplications,
  getUserFavorites,
  submitApplication,
  toggleFavorite
} from '@/api/recruit';

// 初始状态
const state = {
  // 招聘岗位列表
  recruitList: [],
  // 招聘岗位详情
  recruitDetail: null,
  // 用户申请记录
  userApplications: [],
  // 用户收藏的岗位
  userFavorites: [],
  // 列表加载状态
  loading: false,
  // 详情加载状态
  detailLoading: false,
  // 提交状态
  submitting: false,
  // 是否还有更多数据
  hasMore: true,
  // 当前页码
  page: 1,
  // 每页条数
  pageSize: 10,
  // 总条数
  total: 0
};

// getter
const getters = {
  // 获取招聘岗位列表
  getRecruitList: state => state.recruitList,
  
  // 获取招聘岗位详情
  getRecruitDetail: state => state.recruitDetail,
  
  // 获取用户申请记录
  getUserApplications: state => state.userApplications,
  
  // 获取用户收藏的岗位
  getUserFavorites: state => state.userFavorites,
  
  // 判断是否有更多数据
  hasMore: state => state.hasMore,
  
  // 获取加载状态
  loading: state => state.loading,
  
  // 获取详情加载状态
  detailLoading: state => state.detailLoading,
  
  // 获取提交状态
  submitting: state => state.submitting,
  
  // 获取分页信息
  pagination: state => ({
    page: state.page,
    pageSize: state.pageSize,
    total: state.total
  })
};

// mutations
const mutations = {
  /**
   * 设置招聘岗位列表
   * @param {Object} state - Vuex状态
   * @param {Array} list - 招聘岗位列表
   */
  SET_RECRUIT_LIST(state, list) {
    state.recruitList = list;
  },
  
  /**
   * 设置招聘岗位详情
   * @param {Object} state - Vuex状态
   * @param {Object} detail - 招聘岗位详情
   */
  SET_RECRUIT_DETAIL(state, detail) {
    state.recruitDetail = detail;
  },
  
  /**
   * 设置用户申请记录
   * @param {Object} state - Vuex状态
   * @param {Array} applications - 用户申请记录
   */
  SET_USER_APPLICATIONS(state, applications) {
    state.userApplications = applications;
  },
  
  /**
   * 设置用户收藏的岗位
   * @param {Object} state - Vuex状态
   * @param {Array} favorites - 用户收藏的岗位
   */
  SET_USER_FAVORITES(state, favorites) {
    state.userFavorites = favorites;
  },
  
  /**
   * 设置加载状态
   * @param {Object} state - Vuex状态
   * @param {Boolean} loading - 加载状态
   */
  SET_LOADING(state, loading) {
    state.loading = loading;
  },
  
  /**
   * 设置详情加载状态
   * @param {Object} state - Vuex状态
   * @param {Boolean} loading - 详情加载状态
   */
  SET_DETAIL_LOADING(state, loading) {
    state.detailLoading = loading;
  },
  
  /**
   * 设置提交状态
   * @param {Object} state - Vuex状态
   * @param {Boolean} submitting - 提交状态
   */
  SET_SUBMITTING(state, submitting) {
    state.submitting = submitting;
  },
  
  /**
   * 设置是否还有更多数据
   * @param {Object} state - Vuex状态
   * @param {Boolean} hasMore - 是否还有更多数据
   */
  SET_HAS_MORE(state, hasMore) {
    state.hasMore = hasMore;
  },
  
  /**
   * 设置分页信息
   * @param {Object} state - Vuex状态
   * @param {Object} pagination - 分页信息
   * @param {Number} pagination.page - 当前页码
   * @param {Number} pagination.pageSize - 每页条数
   * @param {Number} pagination.total - 总条数
   */
  SET_PAGINATION(state, { page, pageSize, total }) {
    state.page = page || state.page;
    state.pageSize = pageSize || state.pageSize;
    state.total = total || state.total;
  },
  
  /**
   * 重置页码
   * @param {Object} state - Vuex状态
   */
  RESET_PAGE(state) {
    state.page = 1;
    state.hasMore = true;
  },
  
  /**
   * 增加页码
   * @param {Object} state - Vuex状态
   */
  INCREMENT_PAGE(state) {
    state.page += 1;
  },
  
  /**
   * 添加收藏
   * @param {Object} state - Vuex状态
   * @param {Number} recruitId - 招聘岗位ID
   */
  ADD_FAVORITE(state, recruitId) {
    const favorite = {
      id: Date.now(),
      userId: 1, // 模拟用户ID
      recruitId,
      createTime: Date.now(),
      recruitInfo: state.recruitList.find(item => item.id === recruitId)
    };
    state.userFavorites.unshift(favorite);
  },
  
  /**
   * 删除收藏
   * @param {Object} state - Vuex状态
   * @param {Number} recruitId - 招聘岗位ID
   */
  REMOVE_FAVORITE(state, recruitId) {
    state.userFavorites = state.userFavorites.filter(
      item => item.recruitId !== recruitId
    );
  }
};

// actions
const actions = {
  /**
   * 获取招聘岗位列表
   * @param {Object} context - Vuex上下文
   * @param {Object} params - 查询参数
   * @returns {Promise} Promise对象
   */
  async fetchRecruitList({ commit, state }, params = {}) {
    try {
      commit('SET_LOADING', true);
      
      // 如果是刷新或第一页，重置页码
      if (params.refresh) {
        commit('RESET_PAGE');
      }
      
      // 构建查询参数
      const queryParams = {
        page: state.page,
        size: state.pageSize,
        ...params
      };
      
      // 调用API获取数据
      const response = await getRecruitList(queryParams);
      
      if (response.code === 200) {
        const { total, list } = response.data;
        
        // 设置分页信息
        commit('SET_PAGINATION', { total });
        
        // 判断是否还有更多数据
        const hasMore = state.page * state.pageSize < total;
        commit('SET_HAS_MORE', hasMore);
        
        // 如果是第一页或刷新，直接替换列表；否则追加到列表
        if (state.page === 1 || params.refresh) {
          commit('SET_RECRUIT_LIST', list);
        } else {
          commit('SET_RECRUIT_LIST', [...state.recruitList, ...list]);
        }
        
        return { success: true, data: list };
      }
      
      return { success: false, message: response.message };
    } catch (error) {
      console.error('获取招聘岗位列表失败', error);
      return { success: false, message: '获取招聘岗位列表失败' };
    } finally {
      commit('SET_LOADING', false);
    }
  },
  
  /**
   * 加载更多招聘岗位
   * @param {Object} context - Vuex上下文
   * @param {Object} params - 查询参数
   * @returns {Promise} Promise对象
   */
  async loadMoreRecruits({ commit, dispatch, state }, params = {}) {
    if (!state.hasMore || state.loading) {
      return { success: false, message: '没有更多数据了' };
    }
    
    // 增加页码
    commit('INCREMENT_PAGE');
    
    // 获取下一页数据
    return dispatch('fetchRecruitList', params);
  },
  
  /**
   * 获取招聘岗位详情
   * @param {Object} context - Vuex上下文
   * @param {Number} id - 招聘岗位ID
   * @returns {Promise} Promise对象
   */
  async fetchRecruitDetail({ commit }, id) {
    try {
      commit('SET_DETAIL_LOADING', true);
      
      // 调用API获取数据
      const response = await getRecruitDetail(id);
      
      if (response.code === 200) {
        commit('SET_RECRUIT_DETAIL', response.data);
        return { success: true, data: response.data };
      }
      
      return { success: false, message: response.message };
    } catch (error) {
      console.error('获取招聘岗位详情失败', error);
      return { success: false, message: '获取招聘岗位详情失败' };
    } finally {
      commit('SET_DETAIL_LOADING', false);
    }
  },
  
  /**
   * 获取用户申请记录
   * @param {Object} context - Vuex上下文
   * @returns {Promise} Promise对象
   */
  async fetchUserApplications({ commit }) {
    try {
      commit('SET_LOADING', true);
      
      // 调用API获取数据
      const response = await getUserApplications();
      
      if (response.code === 200) {
        commit('SET_USER_APPLICATIONS', response.data.list);
        return { success: true, data: response.data.list };
      }
      
      return { success: false, message: response.message };
    } catch (error) {
      console.error('获取用户申请记录失败', error);
      return { success: false, message: '获取用户申请记录失败' };
    } finally {
      commit('SET_LOADING', false);
    }
  },
  
  /**
   * 获取用户收藏的岗位
   * @param {Object} context - Vuex上下文
   * @returns {Promise} Promise对象
   */
  async fetchUserFavorites({ commit }) {
    try {
      commit('SET_LOADING', true);
      
      // 调用API获取数据
      const response = await getUserFavorites();
      
      if (response.code === 200) {
        commit('SET_USER_FAVORITES', response.data.list);
        return { success: true, data: response.data.list };
      }
      
      return { success: false, message: response.message };
    } catch (error) {
      console.error('获取用户收藏的岗位失败', error);
      return { success: false, message: '获取用户收藏的岗位失败' };
    } finally {
      commit('SET_LOADING', false);
    }
  },
  
  /**
   * 投递简历
   * @param {Object} context - Vuex上下文
   * @param {Object} data - 简历数据
   * @returns {Promise} Promise对象
   */
  async submitApplication({ commit }, data) {
    try {
      commit('SET_SUBMITTING', true);
      
      // 调用API提交数据
      const response = await submitApplication(data);
      
      if (response.code === 200) {
        return { success: true, message: '投递成功' };
      }
      
      return { success: false, message: response.message };
    } catch (error) {
      console.error('投递简历失败', error);
      return { success: false, message: '投递简历失败' };
    } finally {
      commit('SET_SUBMITTING', false);
    }
  },
  
  /**
   * 收藏/取消收藏岗位
   * @param {Object} context - Vuex上下文
   * @param {Object} params - 参数
   * @param {Number} params.id - 招聘岗位ID
   * @param {Boolean} params.isFavorite - 是否已收藏
   * @returns {Promise} Promise对象
   */
  async toggleFavorite({ commit, state }, { id, isFavorite }) {
    try {
      // 调用API提交数据
      const response = await toggleFavorite(id, isFavorite);
      
      if (response.code === 200) {
        // 更新本地状态
        if (isFavorite) {
          commit('REMOVE_FAVORITE', id);
        } else {
          commit('ADD_FAVORITE', id);
        }
        
        return {
          success: true,
          message: isFavorite ? '取消收藏成功' : '收藏成功'
        };
      }
      
      return { success: false, message: response.message };
    } catch (error) {
      console.error('收藏操作失败', error);
      return { success: false, message: '操作失败，请重试' };
    }
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
